package com.example.quiz.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 获取请求的URL
        String url = request.getRequestURI();

        // 登录相关URL无需拦截
        if (url.contains("/user/login") || url.contains("/user/register")) {
            return true;
        }

        // 检查用户是否已登录
        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null) {
            return true;
        }

        // 未登录则跳转到登录页面
        response.sendRedirect(request.getContextPath() + "/user/login");
        return false;
    }
}